﻿#include <fstream>
#include "logwidget.h"
#include <string>
#include <locale>

#include <Windows.h>
#include <stdio.h>
#define DEFAULT_LOG_FILE_NAME		"DSWegameUi"
#ifdef _WIN32
#define FILENAME(x) strrchr(x,'\\')?strrchr(x,'\\')+1:x
#else // _WIN32
#define FILENAME(x) strrchr(x,'/')?strrchr(x,'/')+1:x
#endif

PLOG_SERVICE_CONTEXT g_pStreamCoreLog = NULL;  // 写日志用

static char *GetCurrentMinit()//精确到分钟
{
    char *pchTime;
    pchTime = (char*)malloc(128);
    if (!pchTime)
        return NULL;

    SYSTEMTIME sysTime;
    GetLocalTime(&sysTime);

    memset(pchTime, 0, 128);
    snprintf(pchTime,128,"%d-%d-%d-%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute);

    return pchTime;
}
static char *GetCurrentTimeSec()
{
    char *pchTime;
    pchTime = (char*)malloc(128);
    if (!pchTime)
        return NULL;

    SYSTEMTIME sysTime;
    GetLocalTime(&sysTime);

    memset(pchTime, 0, 128);
    snprintf(pchTime, 128,"%d-%d-%d-%d.%d.%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay,
        sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds);

    return pchTime;
}
static BOOL PWWidecharToMultiBytes(wchar_t* KeySid, char ** ppStr)
{
    DWORD			dwSize = 0;
    *ppStr = NULL;

    dwSize = WideCharToMultiByte(CP_ACP, 0, KeySid, -1, NULL, 0, NULL, NULL);
    *ppStr = (char*)malloc(dwSize * sizeof(char) + 1);
    if (!*ppStr)
        return FALSE;

    int ret = WideCharToMultiByte(CP_ACP, 0, KeySid, -1, *ppStr, dwSize, NULL, NULL);

    if (ret <= 0)
        return FALSE;

    return TRUE;
}

//CSIDL_APPDATA
BOOL InitLogService(char *pFileName, int csidl, PLOG_SERVICE_CONTEXT *ppLogContext)
{
    *ppLogContext = (PLOG_SERVICE_CONTEXT)calloc(1, sizeof(LOG_SERVICE_CONTEXT));
    if (!*ppLogContext)
    {
        return FALSE;
    }

    wchar_t wszFilePath[MAX_PATH] = { 0 };
    int iRet = SHGetSpecialFolderPath(NULL, wszFilePath, csidl, FALSE);
    if (!iRet)
        return FALSE;

    char* pFilePath = NULL;
    PWWidecharToMultiBytes(wszFilePath, &pFilePath);
    if (!pFilePath)
        return FALSE;

    char* pTime = GetCurrentMinit();
    if (!pTime)
        return FALSE;

    if (!pFileName)
        snprintf((*ppLogContext)->chFileName, MAX_PATH,"%s\\DLPcClient\\%s.%s.log", pFilePath, DEFAULT_LOG_FILE_NAME, pTime);
    else
        snprintf((*ppLogContext)->chFileName, MAX_PATH, "%s\\DLPcClient\\%s.%s.log", pFilePath, pFileName, pTime);

    (*ppLogContext)->logMutex = CreateMutex(NULL, FALSE, NULL);
    if ((*ppLogContext)->logMutex == NULL)
        return FALSE;

    if (pFilePath)
    {
        free(pFilePath);
        pFilePath = NULL;
    }
    if (pTime)
    {
        free(pTime);
        pTime = NULL;
    }
    (*ppLogContext)->pFile = NULL;
    return TRUE;
}

static void foo(char *fmt, ...)
{
    va_list ap;
    int d;
    char c, *s;
    va_start(ap, fmt);
    while (*fmt)
        switch (*fmt++) {
        case 's': /* string */
            s = va_arg(ap, char *);
            printf("string %s\n", s);
            break;
        case 'd': /* int */
            d = va_arg(ap, int);
            printf("int %d\n", d);
            break;
        case 'c': /* char */
                  /* need a cast here since va_arg only takes fully promoted types */
            c = (char)va_arg(ap, int);
            printf("char %c\n", c);
            break;
        }
    va_end(ap);
}

int WriteToLog(PLOG_SERVICE_CONTEXT pLogContext, const char *pSourceName, int iLineNum, const char *pLevel, const char *fmt, ...)
{
    if (!pLogContext)
        return -3;

    char chTmp[10240] = { 0 };
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(chTmp, sizeof(chTmp), fmt, ap);
    va_end(ap);

    char chMsg[20480] = { 0 };
    char* pTime = GetCurrentTimeSec();
    if (!pTime)
        return -1;

    //	OutputDebugStringA(chTmp);
#ifdef _DEBUG
    snprintf(chMsg,20480, "[%s][%s][%s:%d].%s \n", pTime, pLevel, FILENAME(pSourceName), iLineNum, chTmp);
#else
    sprintf(chMsg, "[%s][%s].%s \n", pTime, pLevel, chTmp);
#endif // _DEBUG

    DWORD dwWait = WaitForSingleObject(pLogContext->logMutex, 1000);
    if (dwWait != WAIT_OBJECT_0)
    {
        OutputDebugString(L"log service WaitForSingleObject failed \n");
        return -2;
    }
    FILE *pFile;
    if (!fopen_s(&pFile, pLogContext->chFileName, "a+")) {
        fwrite(chMsg, sizeof(char), strlen(chMsg), pFile);
        fclose(pFile);
    }
    ReleaseMutex(pLogContext->logMutex);

    if (pTime)
    {
        free(pTime);
        pTime = NULL;
    }

    return 0;

    /*
    std::ofstream outfile("C:\\Users\\Administrator\\Desktop\\WgProg\\wgsc.log", std::ios::app);

    outfile.imbue(std::locale("", std::locale::all ^ std::locale::numeric));
    outfile << std::string(fmt) << std::endl;
    outfile.close(); */
    return 0;
}

void CloseLogService()
{

}
